/*
 * @(#)LdapAuthentication.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.ldap.core;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.Utility;



/**
   LdapAuthentication.java
   
   This class is responsible for login from Ldap.
   
   @author charlie
   @company         DCIVision Limited
   @creation date   17/12/2004
   @version         $Revision: 1.1.8.2 $
 */

public class LdapAuthenticationHandler {
	private Env env;
	
	protected Log log = LogFactory.getLog(this.getClass().getName());
	
  /**
   * Constructor
   *
   */
	
	public LdapAuthenticationHandler(){
		this.env=new Env();
	}

  /**
   * login - authenticate user form ldap.
   *
   * @param staffCode
   * @param password
   * @return boolean
   */
	
	public boolean login(String staffCode,String password){
		boolean equal=false;
		
    String loginNamePrefix = SystemParameterFactory.getSystemParameter(SystemParameterConstant.LDAP_ACCOUNT_LOGINNAME);
    if(Utility.isEmpty(loginNamePrefix)){
    	loginNamePrefix="cn";
    }    
    
		if(!Utility.isEmpty(env.getFilter())){
		  env.setFilter( "(&(" + loginNamePrefix + "="+staffCode +")("+env.getFilter()+"))");	
		}else{
			env.setFilter(loginNamePrefix+"="+staffCode);	
		}	
		
		String loginName = "";	
		try {
		  LdapMethod ldapMethod=new LdapMethod();
		  NamingEnumeration results = ldapMethod.search(env);   
      /* for each entry print out name + all attrs and values */
      if(results != null && results.hasMore()) {
        SearchResult si = (SearchResult)results.next();      
        loginName = si.getName();   					
			  if (loginName.indexOf(env.getSearchbase()) < 0) {
				  loginName += "," + env.getSearchbase();
				}           
      }else{
        return false;	
      }   
    }catch(Exception e){    	
      log.error(e, e);
      return false;
    }		 
    
 		Hashtable paras= new Hashtable();    
		paras.put(Context.INITIAL_CONTEXT_FACTORY, env.getInitctx());		
		paras.put(Context.SECURITY_AUTHENTICATION,env.getAuthentication());
		paras.put(Context.SECURITY_PRINCIPAL,loginName);
		paras.put(Context.SECURITY_CREDENTIALS,password);					
		paras.put(Context.PROVIDER_URL, env.getService());
		DirContext ctx=null;
	  try {
	    /* get a handle to an Initial DirContext */
	     ctx = new InitialDirContext(paras);
	  }catch(javax.naming.AuthenticationException ae){
      log.error(ae, ae);    		
      return false;
    }catch(javax.naming.NamingException e){    	      
    	//TODO: throws the Exception out to inform user this is a system error (Ldap connection lost?)
      log.error(e, e);
      return false;
    }finally{
    	try{
        if(ctx!=null) ctx.close();	
      }catch(javax.naming.NamingException e){
        //ignore	
      }
    }
		return true;
	}
}
